<?php


namespace app\command;


use app\api\consDir\CommunityConst;
use app\api\services\CommunityService;
use app\api\services\MemberService;
use app\common\models\Community\CommunitySignUser;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class CommunitySignCancel extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('community:sign:cancel')
            ->setDescription('社区订单取消');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info("开始:");
        $checkInSettlementTime = CommunityService::getInstance()->getCommunityConfig('check_in_settlement_time');
        if(empty($checkInSettlementTime)){
            return;
        }
        list($start,$end) = explode('-',$checkInSettlementTime);
        $now = date('H:i');
        if($now < $start || $now > $end){
            $output->info("未到签到时间");
            return;
        }
        $where = [
            ['sign_status', '=', CommunityConst::SIGN_UNUSERED],
            ['expire_at', '<', date('Y-m-d H:i:s')],
        ];
        $list = CommunitySignUser::getInstance()->where($where)->select();
        if(empty($list)){
            return;
        }
        $money = CommunityService::getInstance()->getCommunityConfig('check_in_failed_award');
        foreach ($list as $val) {
            CommunitySignUser::getInstance()->startTrans();
            try{
                if($money > 0){
                    $msg = "签到失败奖励金" . $money . '元';
                    $res = MemberService::getInstance()->addFinanceLog($val->userId, 'sign_return', $money, 3, $msg, '');
                    if(!$res){
                        CommunitySignUser::getInstance()->rollback();
                    }
                }

                $val->refundAmount = $money;
                $val->signStatus = CommunityConst::SIGN_RETURN;
                $val->refundAt = date('Y-m-d H:i:s');
                $val->save();
            }catch (\Exception $e){
                CommunitySignUser::getInstance()->rollback();
                $output->info("异常:".$e->getMessage());
            }
            CommunitySignUser::getInstance()->commit();
        }
        $output->info("结束:");
    }
}